package com.huluobo.a2110mvpimdemo.contact;

import com.huluobo.a2110mvpimdemo.base.BasePresenter;
import com.hyphenate.EMValueCallBack;
import com.hyphenate.chat.EMClient;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by LC on 2023/12/19.
 */
public class ContactPresenter extends BasePresenter<ContactContract.View> implements ContactContract.Presenter {
    List<ContactListItemBean> contactListItemBeans;

    @Override
    public void loadContacts() {
        EMClient.getInstance().contactManager().aysncGetAllContactsFromServer(new EMValueCallBack<List<String>>() {
            @Override
            public void onSuccess(List<String> value) {
                //创建自定义bean的集合
                contactListItemBeans = new ArrayList<>();
                //给返回数据排序
                Collections.sort(value);

                //循环取出每一个value中的值(username)
                for (int i = 0; i < value.size(); i++) {
                    boolean showFirstLetter = false;
                    //第一个item肯定要显示首字符
                    //与上一个对比首字符,如果不同就显示
                    if (i == 0 || value.get(i).charAt(0) != value.get(i - 1).charAt(0)) {
                        showFirstLetter = true;
                    }

                    ContactListItemBean contactListItemBean = new ContactListItemBean(
                            value.get(i),//用户名
                            Character.toUpperCase(value.get(i).charAt(0)),//转换为大写字符的用户名首字符
                            showFirstLetter
                    );
                    //把创建好的bean添加到list中
                    contactListItemBeans.add(contactListItemBean);
                }
                if (isAttach()) {
                    //将赋值好的集合回调给V层
                    getView().onLoadContactSuccess(contactListItemBeans);
                }
            }

            @Override
            public void onError(int error, String errorMsg) {
                if (isAttach()) {
                    getView().onLoadContactFailed(errorMsg);
                }
            }
        });
    }

    @Override
    public void findContact(String username) {
        List<ContactListItemBean> newList = new ArrayList<>();
        for (int i = 0; i < contactListItemBeans.size(); i++) {
            if (username.equals(contactListItemBeans.get(i).getUsername())) {
                ContactListItemBean contactListItemBean = new ContactListItemBean(username, username.charAt(0), true);
                newList.add(contactListItemBean);
            }
        }

        if (isAttach()) {
            if (newList.size() == 0) {
                getView().onFindContactFailed("没有查找到相关用户");
            } else {
                getView().onFindContactSuccess(newList);
            }
        }
    }
}
